(ns ura.data.RoleInfo
  (:require
   [taoensso.telemere :as t]
   [ura.data.Data :refer [executeSql checkDataNull nextId upcaseKey]]
   )
  (:use tupelo.core)
  )


(defn queryRoleById [id]
  (executeSql {:select [:*]
                  :from :ROLE_INFO
                  :where [:= :ID id]})
)


(defn assocAuthData [role]
  (let [roleId (:id role)
        authList (executeSql {:select [:ai.*]
                                 :from [[:AUTH_INFO :ai] [:ROLE_TO_AUTH :rta]]
                                 :where [:and
                                         [:= :ai.id :rta.AUTH_ID]
                                         [:= :rta.ROLE_ID roleId]
                                         ]
                                 })
        ]
    (assoc role :authInfoList authList)
    )
  )


(defn queryRoleInfo "查询角色信息"
  [params]
  (t/log! ["query role by: " params])
  (let [name (:name params)
        code (:code params)
        data (executeSql {:select [:*]
                         :from [:ROLE_INFO]
                         :where [:and
                                 (when (checkDataNull name) [:like :NAME (str "%" name "%")])
                                 (when (checkDataNull code) [:like :CODE (str "%" code "%")])
                                 ]
                         })
        data1 (doall (map assocAuthData data))
        ]
    data1
    )
  )


(defn updateAuth [roleId authIds]
  (if (< 0 (count authIds))
    (let [data (map #(vector roleId %) (set authIds))]
      (t/log! ["save role--auth data: " data authIds])
      (executeSql {:delete-from [:ROLE_TO_AUTH] :where [:= :ROLE_ID roleId]})
      (executeSql {:insert-into [:ROLE_TO_AUTH] :values data})
      )
    (t/log!  ["no role--auth data"])
    )

  )

(defn updateRoleInfo [roleInfo]
  (t/log! ["get update role request: " roleInfo])
  (let [id (:id roleInfo)
        role (upcaseKey (select-keys roleInfo [:name :code :description :state]))
        ]
    (executeSql {:update :ROLE_INFO
                    :set role
                    :where [:= :ID id]
                    })
    (updateAuth id (:authIds roleInfo))
    )
  )

(defn insertRoleInfo [roleInfo]
  (let [newId (nextId "ROLE_INFO_SEQ")
        role (merge (upcaseKey (select-keys roleInfo [:name :code :description :state]))
                    {:ID newId}
                    )
        res (executeSql {:insert-into [:ROLE_INFO]
                            :values [role]
                            })
        ]
    (spy res)
    (updateAuth newId (:authIds roleInfo))
    )
  )

(defn saveRoleInfo [roleInfo]
  (t/log! ["get save role request: " roleInfo])
  (let [isExist (first (queryRoleById (:id roleInfo)))]
    (if isExist
      (updateRoleInfo roleInfo)
      (insertRoleInfo roleInfo)
      )
    )
  )

(defn deleteRoleInfo [id]
  (t/log! ["delete roleInfo by id: " id])
  (executeSql {:delete-from [:ROLE_INFO]
                  :where [:= :ID id]
                  })
)
